import { useContext, useEffect, useState } from 'react';
import type { IPost, IUserClientDetails } from '@/interfaces';
import { toRelativeTime } from '@/lib/tool';
import { useInfiniteQuery } from '@tanstack/react-query';
import { clientQueryUserDetails } from '@/services/api';
import Link from 'next/link';
import classNames from 'classnames';
import useToast from 'hooks/useToast';
import Nodata from '@/app/[locale]/common/nodata/nodata';
import PostName from '@/app/[locale]/common/post/name';
import PostOverview from '@/app/[locale]/common/post/overview';
import PostReadMoreBtn from '@/app/[locale]/common/post/readMore';
import PostTime from '@/app/[locale]/common/post/time';
import Spinner from '@/app/[locale]/component/spinner/spinner';
import { UserIdPageContext } from '@/contexts/user-id';

export default function PostUserIdH5Page(
  this: any,
  {
    type = 'post',
  }: {
    type?: 'post' | 'section' | 'tag';
  },
) {
  const { source, translatedFields } = useContext(UserIdPageContext)!;
  const [pages, setPages] = useState<IPost[]>(source.userDetails.data.content);
  const { show } = useToast();
  const sections = source.userDetails.sections;
  const tags = source.userDetails.tags;

  const clientQueryUserDetailsQuery = useInfiniteQuery(
    ['/users', '/client', source.userDetails.user.id, '/details', 'infinite'],
    async (context) => {
      return (await clientQueryUserDetails({
        id: context.queryKey[2],
        query: context.pageParam,
      })) as IUserClientDetails;
    },
    {
      keepPreviousData: true,
      getPreviousPageParam: (firstPage) => {
        if (!firstPage.data!.pageable.previous) {
          return;
        }
        return {
          page: Math.max(firstPage.data!.pageable.page - 1, 0),
        };
      },
      getNextPageParam: (lastPage) => {
        if (!lastPage.data!.pageable.next) {
          return;
        }
        return {
          page: Math.min(
            lastPage.data!.pageable.page + 1,
            lastPage.data!.pageable.pages,
          ),
        };
      },
      initialData: () => {
        return {
          pages: [source.userDetails],
          pageParams: [{ page: 0 }],
        };
      },
    },
  );

  useEffect(() => {
    if (clientQueryUserDetailsQuery.data) {
      setPages(
        clientQueryUserDetailsQuery.data.pages
          .flatMap((item) => item.data.content)
          .map((item) => {
            item._contentUpdatedOnText = toRelativeTime(item.contentUpdatedOn);
            return item;
          }),
      );
    }
  }, [clientQueryUserDetailsQuery.data]);

  async function onClickLoadMore() {
    try {
      await clientQueryUserDetailsQuery.fetchNextPage();
    } catch (e) {
      show({
        type: 'DANGER',
        message: e,
      });
    }
  }

  return (
    <div className="vstack gap-4">
      {type === 'section' && (
        <div className="my-4 d-flex gap-4 flex-nowrap text-nowrap overflow-x-auto pb-3">
          {sections.map((item) => {
            return (
              <div key={item.id} className="card flex-shrink-0">
                <div className="list-group list-group-flush text-center">
                  <Link
                    href={`/users/${source.userDetails.user.id}?sid=${item.id}`}
                    className={classNames(
                      'list-group-item list-group-item-action py-3',
                      {
                        active: source.queryParams.sectionId === item.id + '',
                      },
                    )}
                  >
                    {item.name}
                  </Link>
                </div>
              </div>
            );
          })}

          <div className="card flex-shrink-0">
            <div className="list-group list-group-flush text-center">
              <Link
                href={`/users/${source.userDetails.user.id}`}
                className={classNames(
                  'list-group-item list-group-item-action py-3',
                  {
                    disabled: sections.length === 0,
                  },
                )}
              >
                {translatedFields.all}
              </Link>
            </div>
          </div>
        </div>
      )}

      {type === 'tag' && (
        <div className="my-4 hstack gap-4 flex-nowrap overflow-x-auto text-nowrap pb-3">
          {tags.map((item) => {
            return (
              <div key={item.id} className="card flex-shrink-0">
                <div className="list-group list-group-flush text-center">
                  <Link
                    href={`/users/${source.userDetails.user.id}?tid=${item.id}`}
                    className={classNames(
                      'list-group-item list-group-item-action',
                      {
                        active: source.queryParams.tagId === item.id + '',
                      },
                    )}
                  >
                    {item.name}
                  </Link>
                </div>
              </div>
            );
          })}

          <div className="card flex-shrink-0">
            <div className="list-group list-group-flush text-center">
              <Link
                href={`/users/${source.userDetails.user.id}`}
                className={classNames(
                  'list-group-item list-group-item-action',
                  {
                    disabled: tags.length === 0,
                  },
                )}
              >
                {translatedFields.all}
              </Link>
            </div>
          </div>
        </div>
      )}

      {pages.map((item) => {
        return (
          <div className="row" key={item.id}>
            <div className="col-12">
              <div className="yw-bg" style={{ height: '0.35rem' }}></div>
            </div>
            <div className="col-12 bg-white rounded-3 py-4">
              <div className="vstack gap-4 align-items-center">
                <PostName
                  item={item}
                  isFwSemibold={false}
                  isJustifyContentCenter
                />

                <PostOverview item={item} bodClassName="my-4" />

                <PostReadMoreBtn
                  item={item}
                  isEdit={source.path.user?.id === item.createdBy}
                />

                <PostTime item={item} />
              </div>
            </div>
          </div>
        );
      })}

      {pages.length === 0 ? (
        <Nodata />
      ) : (
        <LoadMoreBtn
          onClickLoadMore={onClickLoadMore}
          isLoading={clientQueryUserDetailsQuery.isLoading}
        />
      )}
    </div>
  );
}

const LoadMoreBtn = ({
  onClickLoadMore,
  isLoading,
}: {
  onClickLoadMore: () => void;
  isLoading: boolean;
}) => {
  return (
    <div className="row mx-0">
      <div className="col px-0">
        <button
          onClick={onClickLoadMore}
          disabled={isLoading}
          type="button"
          className="btn rounded-pill text-secondary-emphasis w-100"
        >
          {isLoading ? <Spinner /> : <i className="bi bi-three-dots"></i>}
        </button>
      </div>
    </div>
  );
};
